<?php

/**
 * PreContract
 * @author liuch
 * @version 1.0
 * @date 2017-07-28 14:19
 */
class PreContract {

    private $http;
    private $request;
    private $cookieObj;

    public function __construct() {
        require_once ROOT_PATH . 'Http.php';
        require_once ROOT_PATH . 'Cookie.php';
        require_once ROOT_PATH . 'Request.php';
        $this->http = new Http();
        $this->request = new Request();
        $this->cookieObj = new Cookie();
    }

    public function doPreContract($deptName = '', $doctorName = '', $day = array(), $user) {

        //获取门诊列表
        $deptCode = $this->_getDeptCode($deptName);

        //医生信息
        $doctor = $this->_getDoctorInfo($deptCode, $doctorName);

        //判断预约时间医生是否有号
        $result = [
            'do' => false,
            'source' => false,
            'order' => [],
            'doctor' => $doctor,
        ];
        if($doctor) {

            //初始化已预约天
            $preContractDays = [];

            foreach ($doctor['days'] as $value) {
                $workDate = substr($value['workDate'], 0, 10);

                if(in_array($workDate, $day) && $value['allowPrecontractFlag'] && !in_array($workDate, $preContractDays)) {

                    $result['source'] = true;

                    $params = [
                        "deptCode" => $deptCode,
                        "deptName" => $doctor['deptName'],
                        "registerTypeName" => "",
                        "doctor" => $doctor['staffNo'],
                        "workDate" => $value['workDate'],
                        "workType" => $value['dateType'],
                        "clinicName" => "",
                        "clinicCode" => "",
                        "isArmyMan" => "0",
                        "Ip" => "117.25.83.53",
                        "orgId" => ""
                    ];
                    $scheduleTime = $this->http->postRaw($this->request->getUrl('GetScheduleDoctor'), $params);

                    $scheduleTime = $scheduleTime ? json_decode($scheduleTime, true) : [];

                    if (!empty($scheduleTime['data'])) {

                        echo date('Y-m-d H:i:s') . "发现 {$doctor['titleName']} {$doctor['staffName']} 的号源 ：" . json_encode($scheduleTime['data']) . PHP_EOL;

                        $sourceData = $scheduleTime['data'];

                        shuffle($sourceData);

                        foreach ($sourceData as $source) {

                            $p = [
                                'patientName' => $user['patientName'],
                                'time' => $source['time'],
                                'endTime' => $source['endTime'],
                                'deptName' => $doctor['deptName'],
                                'doctorName' => $doctor['staffName'],
                                'telephone' => $user['telephone'],
                                'timePoint' => $source['timePoint'],
                                'deptCode' => $deptCode,
                                'workType' => $value['dateType'],
                                'doctor' => $doctor['staffNo'],
                                'idCardNo' => '',
                                'sourceId' => $source['sourceId'],
                                'waitingNumber' => '',
                                'titleName' => $doctor['titleName'],
                                'branch' => '',
                                'clinicName' => '',
                                'clinicCode' => '',
                                'deptPosition' => '',
                                'identityType' => 'undefined',
                                'isArmyMan' => '0',
                                'Ip' => '117.25.83.53',
                                'verifyId' => '',
                                'countResult' => '',
                                'gender' => $user['sexCode'],
                                'patientId' => $user['patientId'],
                                'icCardNo' => $user['icCardNo'],
                                'cardId' => $user['cardId'],
                            ];
                            $doResponse = $this->http->postRaw($this->request->getUrl('Do'), $p);
                            $doRes = json_decode($doResponse, true);
                            if(isset($doRes['code']) and $doRes['code'] == 0 and $doRes['data']['success']) {
                                $result['do'] = saveOrder([$p['time']]);
                                $result['order'][] = $p['time'];
                                $preContractDays[] = $workDate;
                                break;
                            } else {

                                echo date('Y-m-d H:i:s') . " 参数: " . json_encode($p) . " 结果: {$doResponse}" . PHP_EOL;

                                if (isset($doRes['code']) and $doRes['code'] == 14006) {
                                    $result['source'] = false;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return $result;
    }


    /**
     * @desc 获取部门列表
     * @return array
     * @author liuch
     * @version 1.0
     */
    private function _getDeptCode($deptName) {

        if(!filesize(ROOT_PATH . 'dept.txt') || filemtime(ROOT_PATH . 'dept.txt') < time() - 86400) {
            $deptList = $this->http->postRaw($this->request->getUrl('GetPrecontractDeptList'));

            $deptList = json_decode($deptList, true);
            if($deptList && $deptList['code'] == 0) {

                foreach ($deptList['data'] as $value) {

                    foreach ($value['items'] as $val) {

                        $dept[$val['deptName']] = $val['sortNo'];

                    }
                }
            }

            file_put_contents(ROOT_PATH . 'dept.txt', json_encode($dept));
        } else {
            $dept = json_decode(file_get_contents(ROOT_PATH . 'dept.txt'), true);
        }

        return isset($dept[$deptName]) ? $dept[$deptName] : 0;
    }

    /**
     * @desc 获取门诊预约
     * @author liuch
     * @version 1.0
     */
    private function _getDoctorInfo($deptCode, $doctorName) {

        $params = [
            'deptCode' => $deptCode,
            'deptId' => '',
            'orgId' => '',
        ];

        $scheduleList = $this->http->postRaw($this->request->getUrl('GetScheduleList'), $params);

        $scheduleList = json_decode($scheduleList, true);
        $doctor = [];
        if($scheduleList && $scheduleList['code'] == 0) {
            $doctorList = array_column($scheduleList['data'], null, 'staffName');
            $doctor = $doctorList[$doctorName];
        }

        return $doctor;
    }
}